import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { aiService } from '../../shared/services/ai-service'

export const useBookAnalysisStore = defineStore('bookAnalysis', () => {
  // 状态定义
  const bookPromptTemplates = ref<any[]>([])
  const selectedBookTemplateId = ref<number | null>(null)
  const isBookPromptActive = ref(false)
  const loading = ref(false)
  
  // 计算属性
  const selectedBookTemplate = computed(() => {
    if (!selectedBookTemplateId.value) return null
    return bookPromptTemplates.value.find(template => template.id === selectedBookTemplateId.value) || null
  })
  
  // Actions
  function setBookPromptTemplates(templates: any[]) {
    bookPromptTemplates.value = templates
  }
  
  function setSelectedBookTemplateId(templateId: number | null) {
    selectedBookTemplateId.value = templateId
  }
  
  function setIsBookPromptActive(active: boolean) {
    isBookPromptActive.value = active
  }
  
  function getSelectedBookTemplate() {
    if (!selectedBookTemplateId.value) return null
    return bookPromptTemplates.value.find(template => template.id === selectedBookTemplateId.value) || null
  }
  
  // 加载拆书专用的提示词模板
  async function loadBookPromptTemplates() {
    loading.value = true
    try {
      const response = await aiService.getPromptTemplates()
      
      if (response.code === 0 && response.data) {
        // 过滤出拆书相关的提示词模板
        const bookTemplates = response.data.filter((template: any) => {
          // 根据category或tags判断是否为拆书相关模板
          return template.category === 'book-analysis' || 
                 (template.tags && template.tags.includes('拆书')) ||
                 (template.tags && template.tags.includes('book-analysis'))
        })
        
        bookPromptTemplates.value = bookTemplates.map((template: any) => ({
          id: template.id,
          name: template.name,
          content: template.content,
          description: template.description || '',
          category: template.category || '',
          tags: template.tags || ''
        }))
      }
    } catch (error) {
      console.error('加载拆书提示词模板失败:', error);
    } finally {
      loading.value = false
    }
  }
  
  return {
    // 状态
    bookPromptTemplates,
    selectedBookTemplateId,
    isBookPromptActive,
    loading,
    
    // 计算属性
    selectedBookTemplate,
    
    // 方法
    setBookPromptTemplates,
    setSelectedBookTemplateId,
    setIsBookPromptActive,
    getSelectedBookTemplate,
    loadBookPromptTemplates
  }
})